package com.teach.autoconfigure;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.MethodParameter;
import org.springframework.util.Base64Utils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.support.WebDataBinderFactory;
import org.springframework.web.context.request.NativeWebRequest;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.method.support.ModelAndViewContainer;

import com.teach.commons.JsonUtil;
import com.teach.dto.AuthUser;

import lombok.extern.slf4j.Slf4j;

@Slf4j
public class AuthUserHandlerMethodArgumentResolver implements HandlerMethodArgumentResolver {

	@Autowired
	private JsonUtil jsonUtil;
	@Override
	public boolean supportsParameter(MethodParameter parameter) {
		return parameter.getParameterType()==AuthUser.class;
	}

	@Override
	public Object resolveArgument(MethodParameter parameter, ModelAndViewContainer mavContainer,
			NativeWebRequest webRequest, WebDataBinderFactory binderFactory) throws Exception {
		String json = webRequest.getHeader("auth-user");
		try {
			json = new String(Base64Utils.decodeFromUrlSafeString(json));
			log.debug("身份信息：{}",json);
			if(StringUtils.isEmpty(json)) {
				return null;
			}
			return jsonUtil.toObject(json, AuthUser.class);
		}catch (Exception e) {
			log.debug("获取请求头中的auth-user并转成AuthUser对象失败: "+json,e);
			return null;
		}
	}

}
